package com.redis.test03;

import com.alibaba.fastjson.JSON;
import com.redis.test02.MyRedisUtil;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 作者: LCG
 * 日期: 2019/9/17 14:09
 * 描述: Zk分布式锁测试
 */
@Component
public class TestZkService {

    @Autowired
    private TestMapper testMapper;

    private RetryPolicy retryPolicy=new ExponentialBackoffRetry(1000,3);

    public void lockStock() throws Exception {

        CuratorFramework curatorFramework=CuratorFrameworkFactory.newClient("192.168.137.1:2181",retryPolicy);

        curatorFramework.start();

        InterProcessMutex interProcessMutex=new InterProcessMutex(curatorFramework,"/YYY/lock_");

        interProcessMutex.acquire();//获取锁

         Map<String, Object> byId = testMapper.getById(1L);

         Object stock = byId.get("stock");

         byId.put("stock",Integer.valueOf(stock.toString())-1);

        testMapper.updateGoodsStock(byId);

        interProcessMutex.release();//释放锁

        curatorFramework.close();

    }


}
